from alpha.models import Building
from alpha.models import Room
from alpha.models import TimeBlock
from alpha.models import Course
from alpha.models import Thread
from alpha.models import Comment
from alpha.models import Section
from alpha.models import SectionTimeBlock
from django.http import HttpResponse
import json
import datetime
from django.shortcuts import render_to_response

def get_time():
  # TODO: Doesn't account for changes in DST
  return (datetime.datetime.utcnow() - datetime.timedelta(hours=7)).time()
  
def get_time_of_day(tod=None):
  # Return morning, day, noon, evening, night, depending on time of day
  VALID_TIMES = ['morning', 'day', 'noon', 'evening', 'night', 'sunset']
  if tod is None:
    current_time = get_time()
    if current_time < datetime.time(hour=6):
      return 'night'
    elif current_time < datetime.time(hour=10):
      return 'morning'
    elif current_time < datetime.time(hour=18):
      return 'day'
    elif current_time < datetime.time(hour=21):
      return 'sunset'
    else:
      return 'night'
  elif tod in VALID_TIMES:
    return tod
  else:
    return 'day'
  
def get_today():
  return (datetime.datetime.utcnow() - datetime.timedelta(hours=7)).date()

def get_day_of_week():
  # Retruns 0-6, Monday-Sunday
  return (datetime.datetime.utcnow() - datetime.timedelta(hours=7)).isoweekday() - 1
  
def buildings_json(request):
  response = {}
  response['buildings'] = [b.shortname for b in Building.objects.all().order_by('shortname')]
  return HttpResponse(json.dumps(response))

def buildings(request):
  response = {}
  response['buildings'] = Building.objects.all().order_by('shortname')
  if 'time_of_day' not in request.GET:
    response['time_of_day'] = get_time_of_day()
  else:
    response['time_of_day'] = get_time_of_day(request.GET['time_of_day'])
  return render_to_response('buildings.html', response)

def building(request, building_name):
  response = {}
  _building = Building.objects.get(shortname=building_name)
  rooms = Room.objects.filter(building=_building)
  response['rooms'] = []
  response['building'] = _building
  response['time_blocks'] = TimeBlock.objects.all()
  if 'time_of_day' not in request.GET:
    response['time_of_day'] = get_time_of_day()
  else:
    response['time_of_day'] = get_time_of_day(request.GET['time_of_day'])
  t = get_time()
  if 'time_block' in request.GET:
    time_block = TimeBlock.objects.get(pk=request.GET['time_block'])
  else:
    try:
      time_block, created = TimeBlock.objects.get_or_create(day=get_day_of_week(), 
            start_time__lte=t, end_time__gt=t)
    except Exception:
      time_block = None
  response['time_block'] = time_block
  for room in rooms:
    meta = {}
    if time_block:
      sections = Section.objects.filter(room=room, time_blocks=time_block)
    else:
      sections = []
    meta['sections'] = sections
    response['rooms'].append((room, meta))
  return render_to_response('building.html', response)
  
  
def room(request, building_name, room_name):
  # The page for a room, or section time block
  response = {}
  if 'time_of_day' not in request.GET:
    response['time_of_day'] = get_time_of_day()
  else:
    response['time_of_day'] = get_time_of_day(request.GET['time_of_day'])
  
  # First, lets retrieve the relevent room and section objects
  _room = Room.objects.get(building__shortname=building_name, name=room_name)
  if 'time_block' not in request.GET:
    t = get_time()
    try:
      time_block, created = TimeBlock.objects.get_or_create(day=get_day_of_week(), 
            start_time__lte=t, end_time__gt=t)
    except Exception:
      time_block = None
  else:
    time_block = TimeBlock.objects.get(pk=request.GET['time_block'])
  if time_block:
    sections = Section.objects.filter(room=_room, time_blocks=time_block)
  else:
    sections = []
  response['sections'] = sections
  response['time_block'] = time_block
  response['room'] = _room
  response['time_blocks'] = TimeBlock.objects.all()
  response['url'] = '/%s/%s/' % (_room.building.shortname, _room.name)
  if 'time_block' in request.GET:
    response['url'] += '?time_block=%s' % request.GET['time_block']
  
  # Now lets fetch the section_time_block, associated thread, and comments
  section_time_block = SectionTimeBlock.objects.get(time_blocks=time_block, room=_room)
  thread, created = Thread.objects.get_or_create(created=get_today(), 
      section_time_block=section_time_block)
  comments = Comment.objects.filter(thread=thread)
  response['section_time_block'] = section_time_block
  response['thread'] = thread
  response['comments'] = comments
  
  # Woot we're done
  return render_to_response('room.html', response)
  
  
def about(request):
  response = {}
  if 'time_of_day' not in request.GET:
    response['time_of_day'] = get_time_of_day()
  else:
    response['time_of_day'] = get_time_of_day(request.GET['time_of_day'])
  return render_to_response('about.html', response)
  
  
  
def search(request):
  # Input: query, output: success and url
  response = {}
  try:
    query = request.GET['query']
    buildings = Building.objects.filter(shortname__istartswith=query)
    if buildings:
      building = buildings[0]
      response['success'] = 'true'
      response['url'] = '/building/%s' % building.shortname
    else:
      response['success'] = 'false'
  except Exception:
    response['success'] = 'false'
  finally:
    return HttpResponse(json.dumps(response))